package jmine.tec.persist.schema.impl.elements;

import java.util.ArrayList;
import java.util.List;

import jmine.tec.persist.schema.api.AbstractProcessingSchemaElement;
import jmine.tec.persist.schema.api.ProcessingSchemaElement;
import jmine.tec.persist.schema.api.SchemaColumn;
import jmine.tec.persist.schema.api.SqlDialect;

/**
 * Elemento que representa uma chave primária (primary key)
 * 
 * @author lundberg
 */
public class PrimaryKeyElement extends AbstractProcessingSchemaElement<TableElement> {

    private String name;

    private String tableName;

    private TableElement table;

    private final String[] columns;

    /**
     * Construtor
     * 
     * @param name nome da constraint
     * @param tableName nome da tabela que contém a constraint
     * @param columns colunas que compõe a PK
     * @param parent parent
     */
    public PrimaryKeyElement(String name, String tableName, String[] columns, ProcessingSchemaElement<?> parent) {
        super(parent);
        this.name = name;
        this.tableName = tableName;
        this.columns = columns;
    }

    /**
     * Construtor
     * 
     * @param columns colunas que compõe a PK
     * @param parent parent
     */
    public PrimaryKeyElement(String[] columns, ProcessingSchemaElement<?> parent) {
        this(null, null, columns, parent);
    }

    /**
     * {@inheritDoc}
     */
    public List<String> createStatements(SqlDialect dialect) {
        List<SchemaColumn> cols = new ArrayList<SchemaColumn>(this.columns.length);
        for (String colName : this.columns) {
            cols.add(this.table.findColumn(colName));
        }
        return dialect.renderPrimaryKey(this.tableName, this.name, cols);
    }

    /**
     * Define o nome da chave primária
     * 
     * @param name novo nome
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Obtém o nome da tabela que contém a chave primária
     * 
     * @return nome da tabela
     */
    public String getTableName() {
        return this.tableName;
    }

    /**
     * @param table the table to set
     */
    public void setTable(TableElement table) {
        this.tableName = table.getName();
        this.table = table;
    }

    /**
     * Obtém as colunas que compõe a chave primária
     * 
     * @return colunas que compõe a chave primária
     */
    public String[] getColumns() {
        return this.columns;
    }

    /**
     * Define o nome da chave primária, baseado no alias da tabela que contém a chave.
     * 
     * @param tableElement tabela que contém a chave
     */
    public void process(TableElement tableElement) {
        if (this.name == null || this.name.length() == 0) {
            this.name = String.format("PK_%s", tableElement.getAlias());
        }
    }

}
